package com.scrcu.cloud.wechat.home.endpoint.common.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheUtil {
    private final StringRedisTemplate stringRedisTemplate;
    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public CacheUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }
    
    //逻辑过期
    public void setLogic(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //缓存穿透
    public <R, ID> R queryWithPass(String keyPrefix, ID id, Class<R> type,
                                   Function<ID, R> dbFallback, Long time, TimeUnit unit){

        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        //如果不在缓存中:
        if (json!=null) {
            //缓存中没有找到商铺， 是空值
            return null;
        }
        R r = dbFallback.apply(id);

        if (r==null) {
            stringRedisTemplate.opsForValue().set(key, "",
                    RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            //数据库中没有找到商铺
            return null;
        }
        //存入redis中:
        this.set(key, r, time, unit);
        return r;
    }

    //缓存击穿逻辑过期
    public <R, ID> R QueryWithLogicExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback,
                                          Long time, TimeUnit unit){
        String key = keyPrefix + id;
        String Json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isBlank(Json)) {
            return null;
        }

        //命中， Json反序列化为对象
        RedisData redisLogicData = JSONUtil.toBean(Json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject)redisLogicData.getData(), type);
        LocalDateTime expireTime = redisLogicData.getExpireTime();

        //判断是否过期
        //未过期：返回店铺信息
        if (expireTime.isAfter(LocalDateTime.now())){
            return r;
        }

        //已经过期： 缓存重建
        String lockKey = RedisConstants.LOCK_SHOP_KEY+id;
        boolean islock = tryLock(lockKey);

        // 获取互斥锁成功， 开启独立线程实现缓存重建, 用线程池
        if (islock) {
            executor.submit(() -> {
                try {
                    R tr = dbFallback.apply(id);
//                    String key, Object value, Long time, TimeUnit unit
                    this.setLogic(key, tr, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }
        //获取互斥锁失败，返回过期信息
        return r;
    }

    //缓存击穿问题的互斥解决
    public <R, ID> R QueryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback,
                               Long time, TimeUnit unit) {

        String key = keyPrefix + id;
        String Json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(Json)) {
            return  JSONUtil.toBean(Json, type);
        }
        //如果不在缓存中:
        if (Json!=null) {
            //缓存中没有找到商铺， 是空值
            return null;
        }

        //未命中的时候（缓存击穿）
        //1. 获取互斥锁
        String lock_key = RedisConstants.LOCK_SHOP_KEY + id;
        //2. 判断是否获取成功
        R r = null;
        try {
            //失败，则进入休眠, 并且重试
            if (!tryLock(lock_key)) {
                Thread.sleep(50);
                QueryWithMutex(keyPrefix, id, type, dbFallback, time, unit);
            }

            //成功， 根据id查询数据库
            r = dbFallback.apply(id);
            //不存在
            if (r==null) {
                stringRedisTemplate.opsForValue().set(key, "",
                        RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                //数据库中没有找到商铺
                return null;
            }
            //存在，则存入redis中:
            this.set(key, r, time, unit);
//            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r),
//                    RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //释放互斥锁
            unlock(lock_key);
        }

        //返回
        return r;
    }

    //获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "temps",
                10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

}
